/**
 * Created by Void on 2017/9/7.
 */

import {Directive, ElementRef,Input,Renderer2} from '@angular/core';
import {NavController, Content} from 'ionic-angular';

import {NativeServiceC} from "../../providers/NativeServiceC";

@Directive({
    selector: '[stickyAndroid]'
})
export class StickyAndroidDirective {
    private originDomTop:number;
    @Input()
    content:Content; // 存放数据的model

    constructor(public el:ElementRef,
                protected renderer : Renderer2,
                protected nativaservice:NativeServiceC) {
        this.renderer.setStyle(this.el.nativeElement, 'zIndex', '100');

    }

    ngAfterViewInit() {
        let ele = this.el.nativeElement;
        // 获取父节点
        let parentNode = this.renderer.parentNode(ele);
        let placeHoldDiv = this.renderer.createElement('div');
        let clientHeight = ele.clientHeight + 'px';
        this.renderer.insertBefore(parentNode,placeHoldDiv,ele);
        this.originDomTop = ele.offsetTop;
        this.content.ionScroll.subscribe(($event:any) => {
            let top = $event.scrollTop;
            // 判断手机 iOS 和 android => ios 使用 ionic 原生的效果(sticky) android 使用本指令的效果
            if(this.nativaservice.isIos()) return;
            let stickyClassName ='stick-item';
            if(top>this.originDomTop){
                this.renderer.setStyle(ele,'position','fixed');
                this.renderer.setStyle(ele,'top','44px');
                this.renderer.setStyle(placeHoldDiv,'height',clientHeight);
            }else{
                this.renderer.removeStyle(ele,'position');
                this.renderer.removeStyle(ele,'top');
                this.renderer.setStyle(placeHoldDiv,'height','0');
            }
        })
    }
}